package com.itheima.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component("springSecurityService")
public class SpringSecurityService implements UserDetailsService{

    @Reference
    private UserService userService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        List<GrantedAuthority> list = new ArrayList<>();
        //1.从userService中查询username得到user  2.调用服务 查询数据库
        User user = userService.findByUsername(username);
        //2.判断user是否为空  如果为空则 return null
        if (user==null)return null;
        //3.user不为空   则获取角色 ,判断角色是否为空, 不为空则 遍历角色 得到 permission
        Set<Role> roles = user.getRoles();
        if (roles!=null&&roles.size()>0){
            for (Role role : roles) {
                list.add(new SimpleGrantedAuthority(role.getKeyword()));
                Set<Permission> permissions = role.getPermissions();
                if (permissions!=null&&permissions.size()>0){
                    for (Permission permission : permissions) {
                        //4.list.add(权限)
                        list.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }
        //5.new 一个userdetail new User(user.getusername,user.getpassword,list);
        //6.返回user
        return new org.springframework.security.core.userdetails.User(
                username,user.getPassword(),list);
    }
}
